<script lang="ts" setup>
import { useStyleStore } from '@/stores/style'
import {
  addArticleApi,
  type ArticleVO,
  articleVO2DTO,
  getArticleApi,
  initArticleVO,
  updateArticleApi,
  uploadArticleImgApi
} from '@/request/api/article'
import type { ResultType } from '@/type/type'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { useGlobalDialog } from '@/hooks'
import { ClassifyEnum, DialogEnum } from '@/enum'
import { hasOneNoEmpty, isEmpty, transformMdToImg } from '@/utils'
import { useSystemStore } from '@/stores/system'
import { useTemporaryStore } from '@/stores/temporary'
import { delMinioFilesApi } from '@/request/api'

const { globalDialog } = useGlobalDialog()
const temporaryStore = useTemporaryStore()
const systemStore = useSystemStore()

const route = useRoute()
const formRef = ref<any>()
const styleStore = useStyleStore()

const rules = {
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  labelId: [{ required: true, message: '标签不能为空', trigger: 'blur' }],
  cover: [{ required: true, message: '封面不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  hasVideo: [{ required: true, message: '不能为空', trigger: 'blur' }],
  isComment: [{ required: true, message: '不能为空', trigger: 'blur' }],
  isRecommend: [{ required: true, message: '不能为空', trigger: 'blur' }],
  origin: [{ required: true, message: '来源不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }]
}

// 获取文章
const article = ref<ArticleVO>(initArticleVO())
const getArticle = (id: number) => {
  getArticleApi(id).then((res: ResultType<ArticleVO>) => {
    article.value = res.data
    temporaryStore.article = articleVO2DTO(article.value)
  })
}

onMounted(async () => {
  const id = Number(route.params.id) || 0
  // 判断是否有未完成的任务
  if (hasOneNoEmpty(temporaryStore.article, ['labelId'])) {
    const text =
      '有未完成的任务是否继续上次的任务？' +
      (temporaryStore.urls.length > 0 ? '取消将会删除文件：' + temporaryStore.urls.join(',') : '')
    await globalDialog(text).then((res: boolean) => {
      // 如果用户选择取消
      if (!res) {
        if (temporaryStore.urls.length > 0) {
          delMinioFilesApi(temporaryStore.urls)
          temporaryStore.initArticle()
        }
        id > 0 ? getArticle(id) : ''
      }
    })
  } else {
    id > 0 ? getArticle(id) : temporaryStore.initArticle()
  }
})

/** 提交按钮 */
function submitForm() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      temporaryStore.article.labelId = temporaryStore.form.labelId

      if (temporaryStore.article.id != undefined) {
        await globalDialog('确定修改 ID 为"' + temporaryStore.article.id + '"的文章?').then(
          (res: boolean) => {
            if (res) {
              updateArticleApi(temporaryStore.article, temporaryStore.urls).then(() => {
                temporaryStore.initArticle()
              })
            }
          }
        )
      } else {
        addArticleApi(temporaryStore.article, temporaryStore.urls).then(
          (res: ResultType<boolean>) => {
            if (res.data) {
              temporaryStore.initArticle()
            }
          }
        )
      }
    }
  })
}

const onUploadImg = async (files: File[], callback: (url: string[]) => void) => {
  const formData = new FormData()
  for (let i = 0; i < files.length; i++) {
    formData.append('files', files[i])
  }
  const { data } = await uploadArticleImgApi(formData)
  if (!isEmpty(data)) {
    temporaryStore.urls.push(...data)
  }
  // 将文件名返回给组件，后台上传文件后在替换，不要上传文件名相同的文件
  callback(data.map((url) => url))
}
</script>

<template>
  <el-container class="size-full p-5" direction="vertical">
    <el-button class="max-w-20 mb-5" type="primary" @click="submitForm">提 交</el-button>
    <el-form ref="formRef" :model="temporaryStore.article" :rules="rules" class="size-full">
      <el-form-item label="标题" prop="title">
        <el-input v-model="temporaryStore.article.title" placeholder="请输入标题" />
      </el-form-item>
      <ClassifyLabelForm :type="ClassifyEnum.ARTICLE" />
      <el-form-item label="封面" prop="cover">
        <el-button
          v-if="temporaryStore.article.cover == undefined"
          @click="systemStore.dialog.article = true"
        >
          选择封面
        </el-button>

        <el-image
          v-else
          :src="temporaryStore.article.cover"
          class="cursor-pointer max-w-64 aspect-video use-radius-sm"
          @click="systemStore.dialog.article = true"
        />
      </el-form-item>
      <el-container class="w-full">
        <el-form-item label="可以评论?" prop="isComment">
          <el-radio-group v-model="temporaryStore.article.isComment">
            <el-radio :value="false">否</el-radio>
            <el-radio :value="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否推荐?" prop="isRecommend">
          <el-radio-group v-model="temporaryStore.article.isRecommend">
            <el-radio :value="false">否</el-radio>
            <el-radio :value="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否启用?" prop="status">
          <el-radio-group v-model="temporaryStore.article.status">
            <el-radio :value="false">否</el-radio>
            <el-radio :value="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-container>
      <el-container class="w-full flex-wrap">
        <el-form-item label="含有视频?" prop="hasVideo">
          <el-radio-group v-model="temporaryStore.article.hasVideo">
            <el-radio :value="false">否</el-radio>
            <el-radio :value="true">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频链接" prop="videoUrl">
          <el-input
            v-model="temporaryStore.article.videoUrl"
            :disabled="!temporaryStore.article.hasVideo"
            placeholder="请输入视频链接"
          />
        </el-form-item>
      </el-container>
      <el-container class="flex-wrap">
        <el-form-item label="密码" prop="password">
          <el-input v-model="temporaryStore.article.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="密码提示" prop="tips">
          <el-input v-model="temporaryStore.article.tips" placeholder="请输入密码提示" />
        </el-form-item>
      </el-container>
      <el-form-item label="来源" prop="origin">
        <el-input v-model="temporaryStore.article.origin" />
      </el-form-item>
      <el-form-item
        label="文章内容（控制图文左右排列请使用：<div><img/><span></div>）"
        label-position="top"
        prop="content"
      >
        <MdEditor
          v-model="temporaryStore.article.content"
          :theme="styleStore.background.bgType"
          class="use-radius-sm pb-3 min-h-[640px]"
          @onFocus="
            temporaryStore.article.content = transformMdToImg(temporaryStore.article.content)
          "
          @uploadImg="onUploadImg"
        />
      </el-form-item>
    </el-form>
  </el-container>

  <DialogTemplate :attribute="DialogEnum.ARTICLE">
    <el-container class="auto-min-column">
      <ImageBox
        v-for="p in systemStore.system.resources"
        :key="p.id"
        :url="p.url"
        class="use-radius-sm cursor-pointer"
        @click="
          () => {
            temporaryStore.article.cover = p.url
            systemStore.dialog.article = false
          }
        "
      />
    </el-container>
  </DialogTemplate>
</template>

<style lang="scss" scoped></style>
